using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace Pitoshka.Tools.EncodingChanger
{
	class Program
	{
		private static string _InputPath;
		public static string InputPath
		{
			get { return _InputPath; }
			set { _InputPath = value; }
		}

		private static List<String> _FileFilters = new List<string>();
		public static List<String> FileFilters
		{
			get { return _FileFilters; }
			set { _FileFilters = value; }
		}

		private static int _FromCodePage = 1252;
		public static int FromCodePage
		{
			get { return _FromCodePage; }
			set { _FromCodePage = value; }
		}

		private static int _ToCodePage = 65001;
		public static int ToCodePage
		{
			get { return _ToCodePage; }
			set { _ToCodePage = value; }
		}




		static void Main(string[] args)
		{
			if (args.Length > 0)
			{
				InputPath = args[0];
				FileFilters.AddRange(args[1].Split(new char[] { ',' }));
				if (args.Length > 2)
				{
					FromCodePage = Int32.Parse(args[2]);

					if (args.Length > 3)
					{
						ToCodePage = Int32.Parse(args[3]);
					}
				}
			}



			Encoding enc = Encoding.GetEncoding(ToCodePage);

			DirectoryInfo di = new DirectoryInfo(InputPath);
			foreach (string filter in FileFilters)
			{
				FileInfo[] files = di.GetFiles(filter, SearchOption.AllDirectories);
				foreach (FileInfo file in files)
				{					
					// Reading
					FileStream readStream = file.OpenRead();
					StreamReader sr = new StreamReader(readStream, Encoding.GetEncoding(FromCodePage));

					string fileContent = sr.ReadToEnd();

					sr.Close();
					readStream.Close();
					readStream.Dispose();


					// Writing
					FileStream writeStream = File.Open(file.FullName, FileMode.Truncate);
					StreamWriter sw = new StreamWriter(writeStream, enc);
					
					sw.Write(fileContent);
					
					sw.Close();
					writeStream.Close();
					writeStream.Dispose();

					Console.WriteLine("File '{0,50}' has been updated", file.FullName);
				}
			}

			Console.ReadKey();
		}
	}
}
